<template>
  <el-dialog title="上传图片"  :close-on-click-modal="false" :visible.sync="show" 
  class="dialog_index dialog_image" id="gallery_upload" :before-close="cancle">
    <el-form v-loading="loading" :rules="rules" ref="form" :model="form">
      <el-form-item label="文件夹：" prop="folder_id" >
        <el-select  v-model="form.folder_id" placeholder="文件夹（必填项）" filterable clearable  
          @focus="getFolderList"  @change="changeProductModelName">
          <el-option v-for="item in folderList" :key="item.id" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片名称：" prop="filename">
        <el-input v-model="form.filename " placeholder="图片名称（非必填项）"></el-input>
      </el-form-item>
      <div class="gallery_image_container"  :style="'height: ' + height_upload +'px' ">
        <el-upload class="gallery_uploader gallery_image " action="/api/api/general/upload"  multiple
          :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, item)"
            :on-error="handleError" :before-upload="beforeUpload"
          :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'image_storage', imageheight: imgH, imagewidth: imgW}" >
            <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
            <p>建议上传.png/.jpg/.jpeg格式，大小≤2M，可上传多个（必填项）</p>
        </el-upload>
        <div class="gallery_image " v-for="(image, idx) in imageList" :key="image">
          <el-image :src="utils.setCdnUrl() + image"></el-image>
          <el-button class="del" @click="delImage(idx)">删除</el-button>
        </div>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    </el-dialog>
</template>

<script>

import { folderList, galleryAdd, galleryDel } from '@/api/gallery/gallery.js'

export default {
  data () {
    return {
      loading: false,
      folderList:[],
      siteList: [],
      form: {
        filename:'',
        folder_id: '',
        id: []
      },
      imageList: [],
      imgH: '',
      imgW: '',
      rules: {
        folder_id: [
          { required: true, message: '字段文件夹为必填项！ ', trigger: 'change' }, 
        ],
        filename: [
          {  max: 24,message: '字段图片名称最多24字符！ ', trigger: 'change' }   
        ]
      },
      height: '',
    }
  },
  props: {
    show: Boolean,
    closeDialog:Function,
  },

  methods: {
    setDetailight(){
      let gallery_upload = document.getElementById('gallery_upload').getElementsByClassName('el-dialog__body')[0].offsetHeight
      let el_form_item =  document.getElementById('gallery_upload').getElementsByClassName('el-form-item')
      let itemH = 48 + 64
      for(let i = 0; i < el_form_item.length; i++){
        itemH += el_form_item[i].offsetHeight
      }
      this.height_upload = gallery_upload - itemH
      this.$forceUpdate()
    },
    delImage (index) {
      this.form.id.splice(index, 1)
      this.imageList.splice(index, 1)
    },
    getFolderList () {
      folderList().then(res=>{
        if(res.state == 1){
          let array = [
            {value: 0, label: "所有图片", id: 0},
            {value: 0, label: "我的图片", id: 0}, 
          ]
          this.folderList = array.concat(res.data)
        }
      })
    },
    
    cancle () {
      if(this.form.id.length > 0){
        this.delForm()
      }
      this.cancleForm()
    },
    cancleForm () {
      this.$emit('closeDialog')
      this.$refs.form.resetFields()
      this.imageList = []
      this.form.id = []
    },
    submitForm () {
      this.$refs.form.validate((valid) => {
        if (valid && this.form.id.length > 0) {
          this.update()
        } else {
          if(valid && this.form.id.length == 0 ){
            this.$message.error('未上传图片')
          }
          return false;
        }
      })
    },
 
    update () {
      let params = JSON.parse(JSON.stringify(this.form) ) 
      params.id = JSON.stringify(this.form.id) 
      galleryAdd(params).then(res=>{
        if(res.state == 1){
          this.$message.success('保存成功')
          this.cancleForm()
        }
      })
    },
    handleSuccess (response) {
      if(response.state ==1 ){
        this.imageList.push(response.data.filePathNameHttp)
        this.form.id.push(response.data.id)
        this.$message.success('上传图片成功')   
         this.setDetailight()
      }else {
        this.$message.error(response.message)
      }
     
    },
    
    handleError(){
      this.$message.error('上传图片失败')   
    },
    beforeUpload(file){
      let that = this
      if(file.type !== 'image/jpeg' && file.type !== 'image/jpg' &&  file.type !== 'image/png'){
        this.$message.error("仅支持.jpg/.jpeg/.png格式的图片")
        return false
      }
      const isLt2M = file.size / 1024  <=  2048;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过2M")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          console.log(img.width,img.height)
          // let valid = img.width == '1920' &&   img.height == '937' ;
          let valid = true
          valid ? resolve() : reject();
          that.imgW = img.width
          that.imgH = img.height
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        // that.$message.error('上传图标尺寸为1920*937px')
        return Promise.reject()
      })
      return isSize
    },
    delForm(){
      let params = {
        del_id: JSON.stringify(this.form.id) 
      }
      galleryDel(params).then(res=>{
        if(res.state == 1){
          // this.cancle()
          // this.$message.success('删除成功')
        }
      })

    }
  
  }

}
</script>

<style>

</style>